<template>
  <div id="manufacturerDiv">
    <Breadcrumb content="生产商维护" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="65">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findManufacturerList" @keyup="keyupEnter" @search-click="findManufacturerList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findManufacturerList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addManufacturerDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteManufacturer"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="manufacturerTableRef" class="mytable-scrollbar manufacturerTableClazz" border="inner" align="center" height="auto" :data="manufacturerList" :loading="tloading" @current-change="manufacturerRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :row-style="rowStyle" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="manuCode" title="代码" width="80">
                <template #default="{ row }">
                  <span>{{ row.manuCode }}</span>
                </template>
              </vxe-column>
              <vxe-column field="manuName" title="名称" width="200">
                <template #default="{ row }">
                  <span>{{ row.manuName }}</span>
                </template>
              </vxe-column>
              <vxe-column field="alias" title="简称" width="100">
                <template #default="{ row }">
                  <span>{{ row.alias }}</span>
                </template>
              </vxe-column>
              <vxe-column field="inputCode" title="助记符" width="100">
                <template #default="{ row }">
                  <span>{{ row.inputCode }}</span>
                </template>
              </vxe-column>
              <vxe-column field="contact" title="联系人" width="100">
                <template #default="{ row }">
                  <span>{{ row.contact }}</span>
                </template>
              </vxe-column>
              <vxe-column field="phone" title="电话" width="100">
                <template #default="{ row }">
                  <span>{{ row.phone }}</span>
                </template>
              </vxe-column>
              <vxe-column field="address" title="地址" width="120">
                <template #default="{ row }">
                  <span>{{ row.address }}</span>
                </template>
              </vxe-column>
              <vxe-column field="homePage" title="主页" width="100">
                <template #default="{ row }">
                  <span>{{ row.homePage }}</span>
                </template></vxe-column>
              <vxe-column field="email" title="电子邮件" width="100">
                <template #default="{ row }">
                  <span>{{ row.email }}</span>
                </template></vxe-column>
              <vxe-column field="isStatic" title="是否停用" width="80">
                <template #default="{ row }">
                  <span>{{ row.isStop ? '停用' : '在用' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="remark" title="说明" width="300">
                <template #default="{ row }">
                  <span>{{ row.remark }}</span>
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="50">
                <template #default="{ row }">
                  <span>{{ row.seq }}</span>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="35">
          <el-tabs type="border-card">
            <el-tab-pane label="基础信息">
              <el-form ref="manufacturerFormRef" :model="manufacturerForm" :rules="manufacturerFormRule" label-width="100px" class="form-input-m" inline-message>
                <el-row>
                  <el-col :span="12">
                    <el-form-item prop="manuCode" label="生产商代码">
                      <el-input type="text" v-model="manufacturerForm.manuCode" placeholder="请输入生产商代码" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="manuName" label="生产商名称">
                      <el-input type="text" v-model="manufacturerForm.manuName" placeholder="请输入生产商名称	" clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item prop="alias" label="生产商简称">
                      <el-input type="text" v-model="manufacturerForm.alias" placeholder="请输入生产商简称" @blur="getBdsResult()" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="inputCode" label="助记符">
                      <el-input type="text" v-model="manufacturerForm.inputCode" placeholder="请输入助记符" clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="是否停用" prop="isStatic">
                      <el-switch v-model="manufacturerForm.isStop" inline-prompt active-text="是" inactive-text="否"></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="contact" label="联系人">
                      <el-input type="text" v-model="manufacturerForm.contact" placeholder="请输入联系人" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="phone" label="电话">
                      <el-input type="text" v-model="manufacturerForm.phone" placeholder="请输入电话" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="address" label="地址">
                      <el-input type="text" v-model="manufacturerForm.address" placeholder="请输入地址" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="homePage" label="主页">
                      <el-input type="text" v-model="manufacturerForm.homePage" placeholder="请输入主页" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="email" label="电子邮件">
                      <el-input type="text" v-model="manufacturerForm.email" placeholder="请输入电子邮件" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="remark" label="备注">
                      <el-input type="textarea" v-model="manufacturerForm.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="seq" label="顺序">
                      <el-input-number v-model="manufacturerForm.seq" :min="1" :max="1000" />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button type="primary" @click="saveManufacturer('manufacturerFormRef')">保存</el-button>
                        <el-button type="default" @click="resetForm()">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式

// 全局变量定义区 ==========
// 根据质控规则的关键字查询
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let manufacturerList: any = reactive([]);
let sltPurpose: any = ref({});

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 右侧基本信息表单
let manufacturerForm = reactive({
  id: null,
  manuCode: '',
  manuName: '',
  inputCode: '',
  alias: '',
  address: '',
  contact: '',
  phone: '',
  remark: '',
  email: '',
  homePage: '',
  isStop: false,
  seq: 1,
  orgId: ''
});

let manufacturerFormRule = {
  manuName: [
    {
      required: true,
      message: '请输入生产商名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findManufacturerList(); // 获取质控规则表格数据
});

function findManufacturerList() {
  tloading.value = true;
  manufacturerList.length = 0; //放入数据前清空数据
  const url = '/api/eq/manufacturer/findManufacturerPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      manufacturerList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = manufacturerList.find((k) => k.id == sltPurpose.value.id);
      if (isEmpty(kn)) {
        manufacturerRowClick({ row: manufacturerList[0] }); //默认选中第一条数据
      } else {
        manufacturerRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function valueChangeEvent() {
  findManufacturerList();
}

function saveManufacturer(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (manufacturerForm.id === null) {
      const url = '/api/eq/manufacturer/addManufacturer';
      const manufacturer = {
        manuCode: manufacturerForm.manuCode,
        manuName: manufacturerForm.manuName,
        inputCode: manufacturerForm.inputCode,
        alias: manufacturerForm.alias,
        address: manufacturerForm.address,
        contact: manufacturerForm.contact,
        phone: manufacturerForm.phone,
        remark: manufacturerForm.remark,
        email: manufacturerForm.email,
        homePage: manufacturerForm.homePage,
        isStop: manufacturerForm.isStop,
        seq: manufacturerForm.seq,
        orgId: manufacturerForm.orgId
      };
      proxy.$http
        .post(url, manufacturer)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          clearForm();
          sltPurpose.value.id = res.data.id;
          findManufacturerList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/eq/manufacturer/editManufacturer';
      const manufacturer = {
        id: manufacturerForm.id,
        manuCode: manufacturerForm.manuCode,
        manuName: manufacturerForm.manuName,
        inputCode: manufacturerForm.inputCode,
        alias: manufacturerForm.alias,
        address: manufacturerForm.address,
        contact: manufacturerForm.contact,
        phone: manufacturerForm.phone,
        remark: manufacturerForm.remark,
        email: manufacturerForm.email,
        homePage: manufacturerForm.homePage,
        isStop: manufacturerForm.isStop,
        seq: manufacturerForm.seq,
        orgId: manufacturerForm.orgId
      };
      proxy.$http
        .post(url, manufacturer)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          sltPurpose.value.id = res.data.id;
          setTimeout(() => {
            clearForm();
            findManufacturerList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}
function deleteManufacturer() {
  const sltManufacturers = (proxy.$refs.manufacturerTableRef as any).getCheckboxRecords();
  if (!(sltManufacturers.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delManufacturerList = sltManufacturers.filter((p: any) => !isEmpty(p.id));
        if (delManufacturerList.length > 0) {
          const data = { manufacturerList: delManufacturerList };
          const url = '/api/eq/manufacturer/batchDeleteManufacturerList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findManufacturerList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeManufacturerList = sltManufacturers.filter((p: any) => isEmpty(p.id));
        if (removeManufacturerList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.manufacturerTableRef;
          if ($Xtable) {
            for (const removeRow of removeManufacturerList) {
              manufacturerList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findManufacturerList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findManufacturerList();
}

// 点击设计模式表格当前行触发右侧表单变化
function manufacturerRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.manufacturerTableRef as any).setCurrentRow(row);
    setManufacturerForm(row);
  }
}

// 新建
function addManufacturerDialog() {
  clearForm();
  sltPurpose.value = {};
  (proxy.$refs.manufacturerTableRef as any).clearCurrentRow();
}

// 清空中间规则弹框表单
function clearForm() {
  manufacturerForm.id = null;
  manufacturerForm.manuCode = '';
  manufacturerForm.manuName = '';
  manufacturerForm.inputCode = '';
  manufacturerForm.alias = '';
  manufacturerForm.address = '';
  manufacturerForm.contact = '';
  manufacturerForm.phone = '';
  manufacturerForm.remark = '';
  manufacturerForm.email = '';
  manufacturerForm.homePage = '';
  manufacturerForm.isStop = false;
  manufacturerForm.seq = page.totalResult + 1;
  manufacturerForm.orgId = '';
}
function resetForm() {
  manufacturerForm.manuCode = '';
  manufacturerForm.manuName = '';
  manufacturerForm.inputCode = '';
  manufacturerForm.alias = '';
  manufacturerForm.address = '';
  manufacturerForm.contact = '';
  manufacturerForm.phone = '';
  manufacturerForm.remark = '';
  manufacturerForm.email = '';
  manufacturerForm.homePage = '';
  manufacturerForm.isStop = false;
  manufacturerForm.seq = page.totalResult + 1;
  manufacturerForm.orgId = '';
}
// 编辑当前行规则
function setManufacturerForm(row: any) {
  manufacturerForm.id = row.id;
  manufacturerForm.manuCode = row.manuCode;
  manufacturerForm.manuName = row.manuName;
  manufacturerForm.inputCode = row.inputCode;
  manufacturerForm.alias = row.alias;
  manufacturerForm.address = row.address;
  manufacturerForm.contact = row.contact;
  manufacturerForm.phone = row.phone;
  manufacturerForm.remark = row.remark;
  manufacturerForm.email = row.email;
  manufacturerForm.homePage = row.homePage;
  manufacturerForm.isStop = row.isStop;
  manufacturerForm.seq = row.seq;
  manufacturerForm.orgId = row.orgId;
  sltPurpose.value = row;
}

// 停用的行 红色背景高亮
const rowStyle = ({ row, rowIndex }) => {
  if (row.isStop) {
    return {
      backgroundColor: '#ffd5d5',
      color: 'red'
    };
  }
};

function getBdsResult() {
  manufacturerForm.inputCode = funBdsJsResult('firstPinYinFun', manufacturerForm.alias);
}
</script>

<style lang="scss" scoped>
#manufacturerDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px - 30px);
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
